#version 440
//When specifying only a fragment shader, the texture coordinates are passed in from the built-in vertex shader as vec2 qt_TexCoord0 at location 0
//如果仅提供片段着色器，纹理坐标会从内置的顶点着色器传递，位置为0
layout(location = 0) in vec2 qt_TexCoord0;
//The fragment shader must have a vec4 output at location 0 (typically called fragColor)
layout(location = 0) out vec4 fragColor;
layout(std140, binding = 0) uniform buf {
    mat4 qt_Matrix;
    float qt_Opacity;
    float width;
    float height;
};

//Samplers must use binding points starting from 1
// layout(binding = 1) uniform sampler2D source;

// from https://iquilezles.org/articles/distfunctions
float roundedBoxSDF(vec2 CenterPosition, vec2 Size, float Radius) {
    return length(max(abs(CenterPosition)-Size+Radius,0.0))-Radius;
}

void main(void) {
    //将归一化坐标0.0f~1.0f转换为实际像素坐标
    //同时将左下角坐标原点转换为左上角坐标原点
    vec2 pos = vec2(qt_TexCoord0.x * width, (1-qt_TexCoord0.y) * height);
    // The pixel space scale of the rectangle.
    vec2 size = vec2(width-40, height-40);

    // the pixel space location of the rectangle.
    vec2 location = vec2(width/2,height/2);

    // How soft the edges should be (in pixels). Higher values could be used to simulate a drop shadow.
    float edgeSoftness  = 1.0f;

    // The radius of the corners (in pixels).
    float radius = 6.0f;

    // 计算坐标到圆角矩形边缘的距离
    float distance = roundedBoxSDF(pos.xy - location , size / 2.0f, radius);

    // Smooth the result (free antialiasing).
    float smoothedAlpha =  1.0f-smoothstep(0.0f, edgeSoftness * 2.0f,distance);

    // Return the resultant shape.
    vec4 quadColor		= mix(vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 1.0f, smoothedAlpha), smoothedAlpha);

    // Apply a drop shadow effect.
    float shadowSoftness = 20.0f;
    vec2 shadowOffset    = vec2(0.0f, 5.0f);
    float shadowDistance = roundedBoxSDF(pos.xy - location + shadowOffset , size / 2.0f, radius);
    float shadowAlpha    = 1.0f-smoothstep(-shadowSoftness, shadowSoftness, shadowDistance);
    vec4 shadowColor     = vec4(0.4f, 0.4f, 0.4f, 1.0f);
    fragColor            = mix(quadColor, shadowColor, shadowAlpha - smoothedAlpha);
}
